const Queue = require('bull');
const { setQueues } = require('bull-board');
const taskQueueError = require('./error/taskqueueerror');
const redisConfig = require('../../config/redis.json');
const timeTool = require('./tool/time');

const redisConnectionConfig = {
    host: redisConfig.host,
    port: redisConfig.port,
    password: redisConfig.password,
    db: process.env.NODE_ENV === 'release' ? redisConfig.release_bull_queue_db_index : redisConfig.bull_queue_db_index
};

async function createQueue (queueName) {
    const queue = new Queue(queueName, {
        redis: redisConnectionConfig
    });
    setQueues(queue);
    return queue;
}

async function addQueueProcessor (queue, processorFunc) {
    queue.process(processorFunc);
    return queue;
}

async function addJob (queue, jobData) {
    return queue.add(jobData, {
        removeOnComplete: false
    });
}

async function addTimerJob (queue, jobData, executeTime) {
    const currentTime = timeTool.getCurrentTimestamp();
    if (executeTime < currentTime) {
        throw new taskQueueError.TimerJobError('time has expired');
    }
    return queue.add(jobData, {
        delay: (executeTime - currentTime) * 1000,
        removeOnComplete: false
    });
}

module.exports = {
    createQueue,
    addJob,
    addQueueProcessor,
    addTimerJob
};
